package com.rhok.wthru_client;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.google.android.maps.GeoPoint;
import com.rhok.utils.LocationUtils;
import com.rhok.utils.LocationUtils.MyLocationListener;
import com.rhok.wthru_client.servermsgs.ServerMessageShareLocation;

public class ApproveLocationRequestActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_approve_location_request);
		Button approveBtn = (Button) (findViewById(R.id.approveBtn));
		Button declineBtn = (Button) (findViewById(R.id.declineBtn));

		approveBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				GlobalConfiguration gc = GlobalConfiguration
						.getInstance(getApplicationContext());

				Location myLocation = gc.getLastKnownLocation();

				if (myLocation == null) {
					registerToLocationChangedEvent();
				} else {
					sendLocation(myLocation, false);
				}
			}
		});

		declineBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sendLocation(null, true);

			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_approve_location_request,
				menu);
		return true;
	}

	private void sendLocation(Location myLocation, boolean declined) {

		ServerMessageShareLocation smsl = new ServerMessageShareLocation(
				getApplicationContext());

		if (!declined) {
			GeoPoint gp = LocationUtils.locationToPoint(myLocation);
			smsl.setMyLocation(gp);
		}
		smsl.setDeclined(declined);
		smsl.send();
	}

	private void registerToLocationChangedEvent() {

		LocationUtils.waitForLocation(new MyLocationListener() {

			@Override
			public void locationReceived(Location location) {
				sendLocation(location, true);
			}
		}, getApplicationContext());
	}

}
